package com.nothing.service.run;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import com.ifast.hessian.domain.FaceSearchHassanResult;
import com.nothing.controller.ShowCheckFaceController;
import com.nothing.controller.WebCamPreviewController;
import com.nothing.domain.UserFaceInfo;
import com.nothing.dto.FaceSearchResult;
import com.nothing.hessian.service.CheckFaceService;
import com.nothing.service.UserFaceInfoService;
import com.nothing.util.ExcutorUtil;
import com.nothing.view.FxmlView;
import com.xiaoleilu.hutool.date.DateUtil;

import cn.hutool.core.collection.CollectionUtil;
import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;
/**
 * 
 * @author shíQíang㊚
 *
 */
public class CheckFaceBack implements Runnable {

	private LinkedBlockingQueue<BufferedImage> queue;// 阻塞队列
	private AtomicInteger count;
	private ImageView faceOne;
	private ImageView faceTwo;
	private ImageView faceThree;
	private ImageView faceFour;
	private ImageView faceFive;
	private CheckFaceService checkFaceService;
	private UserFaceInfoService userFaceInfoService;
	private WebCamPreviewController webCam;
	
	public CheckFaceBack(LinkedBlockingQueue<BufferedImage> queue,WebCamPreviewController webCam,CheckFaceService checkFaceService,
			UserFaceInfoService userFaceInfoService, AtomicInteger count, ImageView faceOne, ImageView faceTwo,
			ImageView faceThree, ImageView faceFour, ImageView faceFive) {
		this.queue = queue;
		this.webCam = webCam;
		this.checkFaceService = checkFaceService;
		this.userFaceInfoService = userFaceInfoService;
		this.count = count;
		this.faceOne = faceOne;
		this.faceTwo = faceTwo;
		this.faceThree = faceThree;
		this.faceFour = faceFour;
		this.faceFive = faceFive;
	}

	@Override
	public void run() {
		try {
			while (ExcutorUtil.toCheck) {
				BufferedImage data = queue.take();//.poll(2, TimeUnit.SECONDS);// 有数据时直接从队列的队首取走，无数据时阻塞，在2s内有数据，取走，超过2s还没数据，返回失败
				if (null != data) {
					 
					System.out.println("查询人脸拿到数据");
					List<FaceSearchHassanResult> usersInDb = checkFaceService.toCheck(WebCamPreviewController.groupId);
					 
					
					if (CollectionUtil.isNotEmpty(usersInDb)) {
						//WebCamPreviewController.toCheck = false;
						//doUpdateUserInfo(usersInDb); 
						//showFace(data,usersInDb);
						//弹出
						//checkSuccess(usersInDb, hasCheckedFace);
					}
					data.flush();
					System.out.println("检验人脸数据完成");
				} else {
					System.out.println("查询人脸队列中无数据...");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void doUpdateUserInfo(List<FaceSearchResult> usersInDb){ 
		List<UserFaceInfo> users = userFaceInfoService.selectBatchIds(usersInDb.stream().map(search -> search.getId()).collect(Collectors.toList()));
		if(CollectionUtil.isEmpty(users)){
			return ;
		} 
		users.stream().forEach(user -> {
			user.setChecked(1);
			user.setUpdateTime(DateUtil.now());
			//faceEngineService.delFaceFromCache(user.getGroupId(),user.getId());
		});
		userFaceInfoService.updateBatchById(users);
		Platform.runLater(new Runnable(){
			@Override
			public void run(){
				webCam.search();
			}
		}); 
	}
	private void drow(BufferedImage bufImage,String name,String age,String gender,String group){
		Graphics2D g = bufImage.createGraphics(); 
        g.setBackground(Color.white);
        g.drawImage(bufImage, 0, 0, null); 
        Font font = new Font("微软雅黑", Font.BOLD, 25);   
        g.setFont(font);  
        g.drawString("姓名:"+name,100,100);
        g.drawString("性别:"+gender,100,200);
        g.drawString("年龄:"+age,100,300);
        g.drawString("分组:"+group,100,400);
        g.dispose();
	}
	
	private void showFace(BufferedImage data,List<FaceSearchResult> users) {
		String name = ""; String age = ""; String gender = ""; String group = ""; 
		if (CollectionUtil.isNotEmpty(users)) {
			for (FaceSearchResult user : users) {
				UserFaceInfo userInDb = userFaceInfoService.findByFaceId(user.getFaceId());
				name += userInDb.getName() + "|";
				age += userInDb.getAge() + "|";
				gender += (userInDb.getGender().equals("0") ? "女" : "男") + "|";
				group += " " + "|";
			}
		}
		
		int imgCount = count.incrementAndGet();
		drow(data,name,age,gender,group);
		WritableImage hasCheckedFace = SwingFXUtils.toFXImage(data, null);
		
		if (imgCount % 5 == 0) {
			faceOne.setImage(hasCheckedFace);
		} else if (imgCount % 5 == 1) {
			faceTwo.setImage(hasCheckedFace);
		} else if (imgCount % 5 == 2) {
			faceThree.setImage(hasCheckedFace);
		} else if (imgCount % 5 == 3) {
			faceFour.setImage(hasCheckedFace);
		} else if (imgCount % 5 == 4) {
			faceFive.setImage(hasCheckedFace);
		}
		data.flush();
	}

	@SuppressWarnings("unused")
	private void checkSuccess(List<FaceSearchResult> users, Image findImg) {
		Platform.runLater(new Runnable() {
			@Override
			public void run() {
				String name = "";
				String age = "";
				String gender = "";
				String group = "";

				if (CollectionUtil.isNotEmpty(users)) {
					for (FaceSearchResult user : users) {
						UserFaceInfo userInDb = userFaceInfoService.findByFaceId(user.getFaceId());
						name += userInDb.getName() + "|";
						age += userInDb.getAge() + "|";
						gender += (userInDb.getGender().equals("0") ? "女" : "男") + "|";
						group += " " + "|";
					}
				}

				Stage stage = new Stage();

				FXMLLoader loader = new FXMLLoader(getClass().getResource(FxmlView.SHOW.getFxmlFile()));

				loader.setController(new ShowCheckFaceController(findImg, name, age, gender, group));

				try {

					stage.setScene(new Scene(loader.load()));
					stage.setTitle(FxmlView.SHOW.getTitle());
					stage.show();

				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
	}
}